#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QNetworkDatagram>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    socket = new QUdpSocket(this);

    this->setWindowTitle("cf server");

    connect(socket,&QUdpSocket::readyRead,this,&Widget::proessRequest);

    bool ret = socket->bind(QHostAddress::Any,8080);
    if(!ret)
    {
        QMessageBox::critical(this,"服务器启动出错",socket->errorString());
        return;
    }


}

Widget::~Widget()
{
    delete ui;
}

void Widget::proessRequest()
{
    const QNetworkDatagram& requestDatagram =  socket->receiveDatagram();

    QString request = requestDatagram.data();

    //业务计算
    const QString& response = process(request);

    QNetworkDatagram responseDatagram(response.toUtf8(),requestDatagram.senderAddress(),requestDatagram.senderPort());
    socket->writeDatagram(responseDatagram);

    QString log = "[" + requestDatagram.senderAddress().toString() + ":"
            + QString::number(requestDatagram.senderPort()) + "] req:" + request
            + ", resp: " + response;

    ui->listWidget->addItem(log);
}

QString Widget::process(const QString &request)
{
    return request;
}

